package org.jeecg.trace.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.report.entity.EqpFaultHistory;
import org.jeecg.trace.dto.*;
import org.jeecg.trace.mapper.FaultStatisticsMapper;
import org.jeecg.trace.service.FaultStatisticsService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class FaultStatisticsServiceImpl implements FaultStatisticsService {
    @Autowired
    private FaultStatisticsMapper faultStatisticsMapper;

    @Autowired
    private CommonAPI commonAPI;

    @Override
    public IPage<FaultStatisticsDTO> pageList(Page<FaultStatisticsDTO> page, Map<String, Object> map) {
        return faultStatisticsMapper.pageList(page,map);
    }

    @Override
    public ModelAndView exportXls(HttpServletRequest request, Map<String, Object> param, Class<FaultStatisticsDTO> faultStatisticsDTOClass, String title) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<FaultStatisticsDTO> page = new Page<FaultStatisticsDTO>(1, 9999);
        // 过滤选中数据
        IPage<FaultStatisticsDTO> faultStatisticsDTOIPage = faultStatisticsMapper.pageList(page, param);
        // Step.2 获取导出数据
        List<FaultStatisticsDTO> records = faultStatisticsDTOIPage.getRecords();
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, faultStatisticsDTOClass);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getUsername(), title);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, records);
        return mv;
    }

    @Override
    public void exportXsl2(HttpServletRequest request, HttpServletResponse response, Map<String,Object> map) {
        //定义easyExcel导出的对象
        ExcelWriter excelWriter = null;
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 8);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //头策略使用默认 设置字体大小
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        try {
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
            ExcelWriterSheetBuilder procHistory = EasyExcel.writerSheet(0, "不良数据统计");
            ExcelWriterSheetBuilder materialHistory = EasyExcel.writerSheet(1, "不良数据明细");
            procHistory.head(FaultStatisticsHeadDTO.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
            materialHistory.head(FaultStatisticsDetailsDTO.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle));
            //查询数据并写入
           List<FaultStatisticsHeadDTO> list = faultStatisticsMapper.getHeadList(map);
            List<FaultStatisticsDetailsDTO> details = faultStatisticsMapper.getDetails(map);
            excelWriter.write(list, procHistory.build());
            excelWriter.write(details,materialHistory.build());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
